import * as THREE from 'three'
// import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
//导入第一人称控制器
import {FirstPersonControls} from 'three/examples/jsm/controls/FirstPersonControls'

let renderer, camera, scene
let axesHelper
let controls
let geometryPlane, materialPlane, plane
let clock = new THREE.Clock()





initRenderer()
initCamera()
initScene()
initMeshes()
initAxesHelper()
initControls()
animate()


window.addEventListener('resize', function () {
    camera.aspect = window.innerWidth / window.innerHeight
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
    controls.handleResize()
})


function initRenderer() {
    renderer = new THREE.WebGLRenderer()
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    document.body.appendChild(renderer.domElement)
}

function initCamera() {
    camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 20000)
    camera.position.set(0, 100, 300)
    camera.lookAt(0,0,0)
}

function initScene(params) {
    scene = new THREE.Scene()
    scene.background = new THREE.Color(0xaaccff)
    scene.fog = new THREE.FogExp2(0xaaccff,0.0007)
}

function initAxesHelper(params) {
    axesHelper = new THREE.AxesHelper(100)
    scene.add(axesHelper)
}

function initMeshes(params) {
    //geometry 
    geometryPlane = new THREE.PlaneGeometry(20000, 20000,127,127);
    geometryPlane.rotateX(-Math.PI / 2)

     //起起伏伏
    const positions = geometryPlane.attributes.position
    //它的属性值可能会经常改变，需要创新绘制，以下代码可以提高性能
    positions.usage = THREE.DynamicDrawUsage;
    for (let i = 0; i < positions.count; i++) { 
        const y = 35 * Math.sin(i / 2)
        positions.setY(i,y)
    }

    //material
    const texture = new THREE.TextureLoader().load('textures/water.jpg')
    //设置颜色差异
    //纹理在水平方向和垂直方向上都会重复平铺，这样可以实现纹理的重复映射效果
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping
    texture.repeat.set(5,5)

   
   

    materialPlane = new THREE.MeshBasicMaterial({
        color:0x33ccff,
        map: texture
    });
    plane = new THREE.Mesh(geometryPlane, materialPlane)
    scene.add(plane)
}


//前进：w(鼠标左键) 后退s(鼠标右键) 左：a 右：d 上：r，下：f
function  initControls(params) {
    controls = new FirstPersonControls(camera, renderer.domElement)
    controls.movementSpeed = 500
    controls.lookSpeed = 0.01
}

function animate(params) {
    requestAnimationFrame(animate)
     render()
}

function render(params) {
    const delta = clock.getDelta()
    const time = clock.getElapsedTime() * 10
    const positions = geometryPlane.attributes.position
    for (let i = 0; i < positions.count; i++) { 
        const y = 35 * Math.sin(i / 5+(time+1)/7)
        positions.setY(i,y)
    }
    //通知更新缓冲区和边界盒等相关信息
    positions.needsUpdate = true
    controls.update(delta)
    renderer.render(scene,camera)
}

